package com.carl.zlds.service.impl;

import com.carl.zlds.tool.common.PageBO;
import com.carl.zlds.tool.util.AssertUtil;
import com.carl.zlds.tool.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carl.zlds.dao.ArticleMapper;
import com.carl.zlds.model.Article;
import com.carl.zlds.pojo.dto.ArticleSearchDTO;
import com.carl.zlds.pojo.dto.SaveArticleDTO;
import com.carl.zlds.pojo.vo.ArticleVO;
import com.carl.zlds.service.IArticleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author carl
 */
@Slf4j
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements IArticleService {
    @Override
    public void saveArticle(Long id, SaveArticleDTO dto) {
        Article article;
        if (id > 0) {
            Wrapper<Article> wrapper = new QueryWrapper<Article>().eq("id", id).eq("weight", 0);
            article = this.baseMapper.selectOne(wrapper);
            AssertUtil.isNull("文章不存在", article);
        } else {
            article = new Article();
        }

        article.setTitle(dto.getTitle());
        article.setContent(dto.getContent());

        if (id > 0) {
            this.baseMapper.updateById(article);
        } else {
            this.baseMapper.insert(article);
        }
    }

    @Override
    public void deleteArticle(Long id) {
        Wrapper<Article> wrapper = new QueryWrapper<Article>().eq("id", id).eq("weight", 0);
        Article article = this.baseMapper.selectOne(wrapper);
        AssertUtil.isNull("文章不存在", article);

        article.setWeight(-1);
        this.baseMapper.updateById(article);
    }

    @Override
    public Map<String, Object> getArticleList(ArticleSearchDTO dto, PageBO pageBO) {
        String limitSql = " limit " + (pageBO.getPage() - 1) * pageBO.getLimit() + ", " + pageBO.getLimit();
        List<ArticleVO> list = this.baseMapper.getArticleList(dto, limitSql);
        Integer count = this.baseMapper.countArticleList(dto, "");

        Map<String, Object> map = new HashMap<>(2);
        map.put("list", list);
        map.put("count", count);

        return map;
    }

    @Override
    public ArticleVO getArticleInfo(Long id) {
        Wrapper<Article> wrapper = new QueryWrapper<Article>().eq("id", id).eq("weight", 0);
        Article article = this.baseMapper.selectOne(wrapper);
        AssertUtil.isNull("文章不存在", article);

        ArticleVO articleVO = new ArticleVO();
        ObjUtil.copy(article, articleVO);
        return articleVO;
    }
}
